/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import ModeloDominio.ChequeDentista;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

/**
 *
 * @author LCF
 */
public class ChequeDentistaController {

    /**
     * <p>The <code>PersistenceContext</code>.</p>
     */
    @PersistenceContext
    private EntityManagerFactory emf;

    public ChequeDentistaController() {
        emf = Persistence.createEntityManagerFactory("SISOPersistence");
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(ChequeDentista chequeDentista) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(chequeDentista);
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findChequeDentista(chequeDentista.getId()) != null) {
                System.out.println("ChequeDentista " + chequeDentista + " already exists.");
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(ChequeDentista cheque) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            cheque = em.merge(cheque);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                int id = cheque.getId();
                if (findChequeDentista(id) == null) 
                    System.out.println("ChequeDentista com id " + id + " nao existe.");
            }
        } finally {
            if (em != null) 
                em.close();
        }
    }

    public void destroy(long id) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ChequeDentista cheque = null;
            try {
                cheque = em.getReference(ChequeDentista.class, id);
                cheque.getId();
            } catch (EntityNotFoundException ex) {
                System.out.println("ChequeDentista com id " + id + " nao existe.");
            }
            em.remove(cheque);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    private ChequeDentista findChequeDentista(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(ChequeDentista.class, id);
        } finally {
            em.close();
        }
    }
}
